import 'package:serverpod/serverpod.dart';

import '../../common/business/auth_services.dart';
import '../jwt.dart';

/// Endpoint for JWT tokens management.
abstract class RefreshJwtTokensEndpoint extends Endpoint {
  /// The authentication tokens token manager.
  ///
  /// This is retrieved from the [AuthServices] instance using the
  /// [AuthServices.getTokenManager] method.
  ///
  /// If a different token manager should be used, override this property.
  late final Jwt jwt = AuthServices.getTokenManager<JwtTokenManager>().jwt;

  /// Creates a new token pair for the given [refreshToken].
  ///
  /// Can throw the following exceptions:
  /// -[RefreshTokenMalformedException]: refresh token is malformed and could
  ///   not be parsed. Not expected to happen for tokens issued by the server.
  /// -[RefreshTokenNotFoundException]: refresh token is unknown to the server.
  ///   Either the token was deleted or generated by a different server.
  /// -[RefreshTokenExpiredException]: refresh token has expired. Will happen
  ///   only if it has not been used within configured `refreshTokenLifetime`.
  /// -[RefreshTokenInvalidSecretException]: refresh token is incorrect, meaning
  ///   it does not refer to the current secret refresh token. This indicates
  ///   either a malfunctioning client or a malicious attempt by someone who has
  ///   obtained the refresh token. In this case the underlying refresh token
  ///   will be deleted, and access to it will expire fully when the last access
  ///   token is elapsed.
  ///
  /// This endpoint is unauthenticated, meaning the client won't include any
  /// authentication information with the call.
  @unauthenticatedClientCall
  Future<AuthSuccess> refreshAccessToken(
    final Session session, {
    required final String refreshToken,
  }) async {
    return jwt.refreshAccessToken(
      session,
      refreshToken: refreshToken,
    );
  }
}
